package com.shlh.saas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.VipPackage;
import com.shlh.saas.mapper.VipPackageMapper;
import com.shlh.saas.service.RechargeRecordService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.VipPackageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * VIP套餐服务实现类
 */
@Service
public class VipPackageServiceImpl implements VipPackageService {
    
    private static final Logger log = LoggerFactory.getLogger(VipPackageServiceImpl.class);

    @Autowired
    private VipPackageMapper vipPackageMapper;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private RechargeRecordService rechargeRecordService;

    @Override
    public List<VipPackage> getAllValidPackages() {
        log.info("开始获取所有有效的VIP套餐列表");
        try {
            List<VipPackage> packages = vipPackageMapper.selectAllValidPackages();
            log.info("成功获取VIP套餐列表，共{}个套餐", packages != null ? packages.size() : 0);
            return packages;
        } catch (Exception e) {
            log.error("获取VIP套餐列表时发生异常: {}", e.getMessage(), e);
            // 返回空列表而不是让异常继续传播
            return new ArrayList<>();
        }
    }

    @Override
    public VipPackage getPackageById(Long id) {
        log.info("开始获取ID为{}的VIP套餐", id);
        try {
            VipPackage vipPackage = vipPackageMapper.selectById(id);
            log.info("成功获取ID为{}的VIP套餐: {}", id, vipPackage != null ? vipPackage.getName() : "未找到");
            return vipPackage;
        } catch (Exception e) {
            log.error("获取ID为{}的VIP套餐时发生异常: {}", id, e.getMessage(), e);
            return null;
        }
    }

    @Override
    @Transactional
    public boolean purchaseVipPackage(String phone, Long packageId) {
        log.info("用户{}开始购买ID为{}的VIP套餐", phone, packageId);
        try {
            // 1. 获取VIP套餐信息
            VipPackage vipPackage = vipPackageMapper.selectById(packageId);
            if (vipPackage == null || vipPackage.getIsDeleted() == 1) {
                log.warn("用户{}尝试购买的套餐ID{}不存在或已被删除", phone, packageId);
                return false;
            }
            log.info("用户{}购买的套餐信息: 名称={}, 等级={}, 价格={}, 有效期={}个月", 
                    phone, vipPackage.getName(), vipPackage.getLevel(), vipPackage.getPrice(), vipPackage.getDuration());
            
            // 2. 更新用户VIP信息
            // 使用套餐定义的有效期
            int months = vipPackage.getDuration() != null ? vipPackage.getDuration() : 1;
            Integer exportQuota  = vipPackage.getExportQuota() != null ? vipPackage.getExportQuota() : 0;
            Integer viewRecords = vipPackage.getViewRecords() != null ? vipPackage.getViewRecords() : 0;
            Integer reverseLookup = vipPackage.getReverseLookup() != null ? vipPackage.getReverseLookup() : 0;
            // 更新用户VIP等级和到期时间
            boolean result = userBalanceService.updateUserVip(phone, vipPackage.getLevel(), months, exportQuota, viewRecords, reverseLookup);
            
            // 3. 创建交易记录
            if (result) {
                // 获取用户当前余额
                UserBalance userBalance = userBalanceService.getUserBalance(phone);
                BigDecimal afterAmount = userBalance != null ? userBalance.getCashBalance() : new BigDecimal("0.00");
                
                // 创建消费记录
                String description = "购买" + vipPackage.getName() + "套餐";
                
                // 更新用户的权限配额
                if (userBalance != null) {
                    // 设置导出次数配额
                    userBalance.setExportQuotaRemaining(vipPackage.getExportQuota());
                    // 设置可查看记录数
                    userBalance.setViewRecordsRemaining(vipPackage.getViewRecords());
                    // 设置反查次数
                    userBalance.setReverseLookupRemaining(vipPackage.getReverseLookup());
                    // 更新用户余额记录
                    userBalanceService.updateById(userBalance);
                    
                    log.info("更新用户{}的权限配额 - 导出次数:{}, 可查看记录数:{}, 反查次数:{}", 
                            phone, vipPackage.getExportQuota(), vipPackage.getViewRecords(), vipPackage.getReverseLookup());
                }
                
                log.info("创建充值记录 - 套餐ID: {}, 套餐等级: {}, 描述: {}", packageId, vipPackage.getLevel(), description);
                
                boolean recordCreated = rechargeRecordService.createRecord(
                    phone,
                    "VIP", // 使用VIP类型
                    vipPackage.getPrice(), // 使用正数表示充值金额
                    afterAmount,
                    description,
                    "alipay", // 默认支付宝支付
                    packageId.intValue() // 确保传递正确的packageId
                );
                
                log.info("用户{}购买VIP套餐交易记录创建结果: {}", phone, recordCreated ? "成功" : "失败");
            }
            
            log.info("用户{}购买VIP套餐结果: {}", phone, result ? "成功" : "失败");
            return result;
        } catch (Exception e) {
            log.error("用户{}购买ID为{}的VIP套餐时发生异常: {}", phone, packageId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public VipPackage getPackageByVipLevel(Integer vipLevel) {
        log.info("开始获取VIP等级为{}的VIP套餐", vipLevel);
        try {
            VipPackage vipPackage = vipPackageMapper.selectOne(new QueryWrapper<VipPackage>()
                    .eq("level", vipLevel)
                    .eq("is_deleted", 0));
            if (vipPackage == null) {
                log.warn("未找到VIP等级为{}的VIP套餐", vipLevel);
                return null;
            }else {
                log.info("成功获取VIP等级为{}的VIP套餐: {}", vipLevel, vipPackage.getName());
                return vipPackage;
            }
        } catch (Exception e) {
            throw new RuntimeException("获取VIP等级为" + vipLevel + "的VIP套餐时发生异常 " , e);
        }
    }
} 